document.addEventListener("DOMContentLoaded", function () {
    const sendButton = document.querySelector(".sendBtn");
    const messageInput = document.querySelector("#message");
    const chatContainer = document.querySelector(".container");

    sendButton.addEventListener("click", function (event) {
        event.preventDefault();
        const message = messageInput.value.trim();

        if (message !== "") {
            fetch("/LR/send_message/", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRFToken": getCookie("csrftoken"),
                },
                body: JSON.stringify({ message: message }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === "success") {
                    const newMessage = document.createElement("div");
                    newMessage.classList.add("message-container", "myself");
                    newMessage.innerHTML = `
                        <img src="${data.user_avatar}" alt="user头像" class="user-avatar">
                        <div class="message-bubble-right">${message}</div>
                        <div style="font-size: small;color:gray;text-align:right">${data.sent_at}</div>
                    `;
                    chatContainer.appendChild(newMessage);
                    messageInput.value = "";
                }
            });
        }
    });

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== "") {
            const cookies = document.cookie.split(";");
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.startsWith(name + "=")) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});
